import sys
import win32crypt
import binascii
import json
import base64
import os
import datetime
import time
import pymsgbox


def encryptionPassword(password):
    """解密密码"""
    pwdHash = win32crypt.CryptProtectData(password.encode('utf-16-le'), u'psw', None, None, None, 0)
    pwdHash_ok = binascii.hexlify(pwdHash)
    pwdHash_ok = str(pwdHash_ok).split("'")[1]
    return pwdHash_ok


def create_rdp(ip, username, password, rdpFilePath):
    enPassword = encryptionPassword(password)
    text = u'''username:s:{username}
password 51:b:{password}
full address:s:{ip}'''.format(username=username, password=enPassword, ip=ip)

    f = open(rdpFilePath, mode='w', encoding='utf-8')
    f.write(text)
    f.close()


def writeLog(text):
    f = open('c:\\tmpRdp\\log.txt', mode='w', encoding='utf-8')
    f.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S' + "\t" + text))
    f.close()



url = sys.argv[1]
writeLog(url)
if url.endswith('/'):
    url = url[0:-1]

i = url.index("//")
b64 = url[i + 2:]
jsonStr = base64.b64decode(b64).decode("utf-8")
loginInfo = json.loads(jsonStr)
ip = loginInfo["ip"]
# writeLog("ip="+ ip)
username = loginInfo["username"]
# writeLog("username="+ username)
password = loginInfo["password"]
loginDate = datetime.datetime.strptime(loginInfo["loginDate"], '%Y-%m-%d')
todayStr = datetime.datetime.now().strftime('%Y-%m-%d')
today = datetime.datetime.strptime(todayStr, '%Y-%m-%d')
if (abs((today - loginDate).days) <= 1):
    # if True: #调试用这句  正式用上面那句
    try:
        if not os.path.exists("c:\\tmpRdp"):
            os.mkdir("c:\\tmpRdp")
        create_rdp(ip, username, password, "c:\\tmpRdp\\tmp.rdp")
        os.system("start mstsc.exe c:\\tmpRdp\\tmp.rdp")
        time.sleep(1)
        os.remove("c:\\tmpRdp\\tmp.rdp")
    except Exception as e:
        pymsgbox.alert(text='请截图给管理员\r\n' + str(e), title='程序错误', button='我知道了')
